'use strict';
/** 
 * controller for User Profile Example
 */
app.controller('adminRoleListCtrl', ["$rootScope", "$scope", "$state", "$timeout", "$interval", "$modal", "$window", "SweetAlert", "i18nService", "uiGridConstants", "uiGridGroupingConstants", "Restangular", "api_user_data", "api_solution", function($rootScope, $scope, $state, $timeout, $interval, $modal, $window, SweetAlert, i18nService, uiGridConstants, uiGridGroupingConstants, Restangular, api_user_data, api_solution) {
    $scope.langs = i18nService.getAllLangs();
    $scope.lang = 'zh-cn';

    i18nService.setCurrentLang($scope.lang);

    var loginUser = $rootScope.user;

    var _ = $window._;
    //$scope.allright=false;
    //$scope.allrightnot=true;
    $scope.gridOptions = {};
    $scope.gridOptions.data = 'myData';
    $scope.gridOptions.enableColumnResizing = true;
    $scope.gridOptions.enableFiltering = false;
    $scope.gridOptions.enableGridMenu = false;
    $scope.gridOptions.enableRowSelection = true;
    $scope.gridOptions.showGridFooter = true;
    $scope.gridOptions.showColumnFooter = false;
    $scope.gridOptions.fastWatch = true;
    $scope.gridOptions.useExternalPagination = true;
    $scope.gridOptions.paginationPageSizes = [10];
    $scope.gridOptions.paginationPageSize = 10;
    $scope.gridOptions.multiSelect = true;

    //$scope.gridOptions.rowTemplate= "<div ng-dblclick=\"grid.appScope.onDblClick(row)\" ng-repeat=\"(colRenderIndex, col) in colContainer.renderedColumns track by col.uid\" ui-grid-one-bind-id-grid=\"rowRenderIndex + '-' + col.uid + '-cell'\" class=\"ui-grid-cell\" ng-class=\"{ 'ui-grid-row-header-cell': col.isRowHeader }\" role=\"{{col.isRowHeader ? 'rowheader' : 'gridcell'}}\" ui-grid-cell></div>";

    $scope.gridOptions.rowIdentity = function(row) {
        return row.id;
    };
    $scope.gridOptions.getRowIdentity = function(row) {
        return row.id;
    };


    // $scope.transferRole = function(roles){
    //   var tempValue="";
    //   angular.forEach(roles,function(item){
    //     if(tempValue!=""){
    //         tempValue = tempValue + "/" ;
    //     }
    //     tempValue = tempValue + item.role;
    //   })
    //   return tempValue;
    // }  
    $scope.transfertype = function(roletype) {
            return (roletype == 0) ? "登录角色" : "流程角色";
        }
        //remote data
    $scope.gridOptions.columnDefs = [{
            name: '操作',
            cellTemplate: '<a class="btn btn-sm btn-info" ng-hide="row.entity.roletype" ' +
                'ng-click="grid.appScope.saveData(row.entity)" tooltip="编辑">' +
                '<i class="fa fa-pencil-square-o"/></a>   ',
            width: 100,
            enableFiltering: false
        },
        { name: 'role', displayName: '角色名', width: 150 },
        { name: 'rolecode', displayName: '角色代码', width: 150 },
        { name: 'roletype', displayName: '角色类型', cellTemplate: '<div class="ui-grid-cell-contents">{{grid.appScope.transfertype(row.entity.roletype)}}</div>', width: 150, enableFiltering: false }
        //'<div class="links cl-effect-1">' +
        //      '<a ng-click="grid.appScope.selectRowFunction(row.entity)" tooltip="编辑" tooltip-placement="left"><i class="fa fa-pencil-square-o"></i></a>'+
        //      '</div>' , width:100, enableFiltering:false}
    ];

    $scope.refresh = function(style, filterData) {
        var filtersData = {
            "assignee": $rootScope.user.id,
            "candidateGroups": $rootScope.user.group[0].id,
            idx: 0,
            sum: 10
        };
        $scope.gridOptions.refresh();
        $scope.refreshData('expand-right', filtersData);
    };

    $scope.resetrole = function(id) {
        var modalInstance = $modal.open({
            templateUrl: 'assets/views/system/user/resetrole.html',
            //       controller: function($scope, $modalInstance, isCreate, Alert){
            //         var apple_selected, tree, treedata_avm, treedata_geography;
            //         $scope.my_tree_handler = function (branch) {
            //           var _ref;
            //           $scope.output = branch.label;
            //           if ((_ref = branch.data) != null ? _ref.description :void 0) {
            //             return $scope.output += '(' + branch.data.description + ')';
            //           }
            //         };
            //         apple_selected = function (branch) {
            //           return $scope.output = branch.label;
            //           console.log("branch.label="+branch.label)
            //         };
            // treedata_avm = [{
            //     label: 'Animal',
            //     children: [{
            //         label: 'Dog',
            //         data: {
            //             description: "man's best friend"
            //         }
            //     }, {
            //         label: 'Cat',
            //         data: {
            //             description: "Felis catus"
            //         }
            //     }, {
            //         label: 'Hippopotamus',
            //         data: {
            //             description: "hungry, hungry"
            //         }
            //     }, {
            //         label: 'Chicken',
            //         children: ['White Leghorn', 'Rhode Island Red', 'Jersey Giant']
            //     }]
            // }, {
            //     label: 'Vegetable',
            //     data: {
            //         definition: "A plant or part of a plant used as food, typically as accompaniment to meat or fish, such as a cabbage, potato, carrot, or bean.",
            //         data_can_contain_anything: true
            //     },
            //     onSelect: function (branch) {
            //         return $scope.output = "Vegetable: " + branch.data.definition;
            //     },
            //     children: [{
            //         label: 'Oranges'
            //     }, {
            //         label: 'Apples',
            //         children: [{
            //             label: 'Granny Smith',
            //             onSelect: apple_selected
            //         }, {
            //             label: 'Red Delicous',
            //             onSelect: apple_selected
            //         }, {
            //             label: 'Fuji',
            //             onSelect: apple_selected
            //         }]
            //     }]
            // }, {
            //     label: 'Mineral',
            //     children: [{
            //         label: 'Rock',
            //         children: ['Igneous', 'Sedimentary', 'Metamorphic']
            //     }, {
            //         label: 'Metal',
            //         children: ['Aluminum', 'Steel', 'Copper']
            //     }, {
            //         label: 'Plastic',
            //         children: [{
            //             label: 'Thermoplastic',
            //             children: ['polyethylene', 'polypropylene', 'polystyrene', ' polyvinyl chloride']
            //         }, {
            //             label: 'Thermosetting Polymer',
            //             children: ['polyester', 'polyurethane', 'vulcanized rubber', 'bakelite', 'urea-formaldehyde']
            //         }]
            //     }]
            // }];
            // treedata_geography = [{
            //     label: 'North America',
            //     children: [{
            //         label: 'Canada',
            //         children: ['Toronto', 'Vancouver']
            //     }, {
            //         label: 'USA',
            //         children: ['New York', 'Los Angeles']
            //     }, {
            //         label: 'Mexico',
            //         children: ['Mexico City', 'Guadalajara']
            //     }]
            // }, {
            //     label: 'South America',
            //     children: [{
            //         label: 'Venezuela',
            //         children: ['Caracas', 'Maracaibo']
            //     }, {
            //         label: 'Brazil',
            //         children: ['Sao Paulo', 'Rio de Janeiro']
            //     }, {
            //         label: 'Argentina',
            //         children: ['Buenos Aires', 'Cordoba']
            //     }]
            // }];
            // $scope.my_data = treedata_avm;
            // $scope.try_changing_the_tree_data = function () {
            //     if ($scope.my_data === treedata_avm) {
            //         return $scope.my_data = treedata_geography;
            //     } else {
            //         return $scope.my_data = treedata_avm;
            //     }
            // };
            // $scope.my_tree = tree = {};
            // $scope.try_async_load = function () {
            //     $scope.my_data = [];
            //     $scope.doing_async = true;
            //     return $timeout(function () {
            //         if (Math.random() < 0.5) {
            //             $scope.my_data = treedata_avm;
            //         } else {
            //             $scope.my_data = treedata_geography;
            //         }
            //         $scope.doing_async = false;
            //         return tree.expand_all();
            //     }, 1000);
            // };


            //           $scope.ok = function() {
            //             $modalInstance.close($scope.entity);                
            //           }; 

            //           $scope.cancel = function() {
            //               $modalInstance.dismiss('cancel');
            //           };
            //       },
            //       size:'lg',
            //       resolve: {
            //         isCreate: function(){
            //           return flag;
            //         },
            //         Alert: function(){
            //           return SweetAlert;
            //         }
            //       }
            //   });
            //   modalInstance.result.then(function(selectedItem) {
            //     if(selectedItem){
            //       // console.log("selectedItem=")   
            //     }
            //   });
            // }
            controller: function($scope, $modalInstance, APIService, uploader, tree_data, currentUser) {

                var typeName;
                $scope.tree_handler = function(branch) {
                    $scope.showknowledgeType = true;
                    $scope.entity.typeName = branch.label;
                    $scope.entity.typeId = branch.id;
                    console.log(branch);
                };

                $scope.uploader = uploader;
                var loadData = function() {

                    $scope.visions = [];
                    $scope.solutionDowpath = APIService.getSolutionDowpath().getRequestedUrl();
                    APIService.findSolutionById(id).then(function(response) {
                        var datas = response.data;
                        $scope.visions = datas;
                        console.log(' datas=' + JSON.stringify(datas));
                        var data = {};
                        for (var i = 0; i < datas.length - 1; i++) {
                            if (id == datas[i].id) {
                                data = datas[i];
                            }
                        }


                    });
                }

                loadData();


                $scope.options = {
                    language: 'zh-cn',
                    allowedContent: true,
                    entities: false
                };
                $scope.uploader = uploader;
                $scope.onReady = function() {
                    // ...

                };



                $scope.ok = function() {
                    $modalInstance.close($scope.entity);
                };

                $scope.cancel = function() {
                    $modalInstance.dismiss('cancel');
                };
            },
            size: 'lg',
            resolve: {
                APIService: function() {
                    return api_solution;
                },
                uploader: function() {
                    return $scope.uploader;
                },

                tree_data: function() {

                    return angular.copy($scope.tree_data);
                },

                currentUser: function() {
                    return loginUser.id;
                }
            }
        });
        modalInstance.result.then(function(selectedItem) {
            if (selectedItem) {}
        });
    }

    $scope.addData = function() {
        $state.go('app.system.form_role', { formKey: 'system_edit_role', service: 'api_user_data' });
    }

    $scope.saveData = function(entity) {
        var modelData = {
            model: {
                role: entity
            }
        };
        console.log("modelData=" + JSON.stringify(modelData));
        $state.go('app.system.form_role', { formKey: 'system_edit_role', service: 'api_user_data', model: JSON.stringify(modelData) });
    };

    $scope.addDataExtra = function() {
        var addIndex = -1;
        angular.forEach($scope.myData, function(item, index) {
            if (angular.isUndefined(item.id)) {
                addIndex = index;
            }
        });
        if (addIndex != -1) {
            SweetAlert.swal({
                title: "警告!",
                text: "新增操作会丢失未提交的新增数据，请先进行保存操作！",
                type: "warning",
                cancelButtonText: "取消",
                showCancelButton: true,
                confirmButtonColor: "#DD6B55",
                confirmButtonText: "继续"
            }, function(isConfirm) {
                if (isConfirm) {
                    $scope.myData.splice(addIndex, 1);
                    //$scope.myData.push({'role':'新角色','rolecode':'new rolecode'});
                }
            });
        } else {
            $scope.myData.push({ 'role': "新角色", 'rolecode': "rolecode" });
        }
    }

    $scope.afterAddData = function(data) {
        api_user_data.addData('role', data).then(function(response) {
            if (response.data) {
                SweetAlert.swal({
                    title: "增加成功!",
                    type: "success",
                    confirmButtonColor: "#007AFF"
                }, function() {
                    $scope.refreshData('expand-right', defaultFilterData);
                });

            } else {
                SweetAlert.swal({
                    title: "操作异常!",
                    text: "系统异常，请稍后重试，或者联系管理员！",
                    type: "error"
                });
            }
        })
    }

    $scope.removeData = function() {
        var rmvList = [];
        angular.forEach($scope.selected.items, function(item) {
            rmvList.push(item.id);
        });
        if (rmvList.length > 0) {
            api_user_data.rmvData('role', rmvList).then(function(response) {
                if (response.data) {
                    SweetAlert.swal({
                        title: "删除成功!",
                        type: "success",
                        confirmButtonColor: "#007AFF"
                    }, function() {
                        $scope.myData = _.reject($scope.myData, function(o) { return _.includes(rmvList, o.id); });
                        $scope.selected = {
                            items: []
                        };
                    });

                } else {
                    SweetAlert.swal({
                        title: "操作异常!",
                        text: "系统异常，请稍后重试，或者联系管理员！",
                        type: "error"
                    });
                }
            })
        }
    }



    $scope.saveDataExtra = function(data) {
        var postData = {
            'role': data
        }
        api_user_data.addData('role', postData).then(function(response) {
            if (response.data) {
                SweetAlert.swal({
                    title: "操作成功!",
                    type: "success",
                    confirmButtonColor: "#007AFF"
                }, function() {
                    var flag = angular.isDefined(data.id);
                    var saveIndex = -1;
                    angular.forEach($scope.myData, function(item, index) {
                        if (item.id == data.id) {
                            saveIndex = index;
                        }
                        if (flag && item.id == data.id) {
                            saveIndex = index;
                        } else if (angular.isUndefined(item.id)) {
                            saveIndex = index;
                        }
                    });
                    if (saveIndex != -1) {
                        $scope.myData[saveIndex] = response.data;
                        //if(flag){
                        $scope.modified.items = []; //_.reject($scope.modified.items, function(o){ return o.id==data.id;})
                        //$scope.modified.items.splice(data,1) 
                        //}                             
                    }
                });

            } else {
                SweetAlert.swal({
                    title: "操作异常!",
                    text: "系统异常，请稍后重试，或者联系管理员！",
                    type: "error"
                });
            }
        })
    }

    $scope.isModify = function(entity) {
        var ret = false;
        if (angular.isUndefined(entity.id)) {
            ret = true;
        } else {
            angular.forEach($scope.modified.items, function(item) {
                if (item.id == entity.id) {
                    ret = true;
                }
            });
        }
        return ret;
    }

    $scope.selected = {
        items: []
    }

    $scope.modified = {
        items: []
    }



    $scope.gridOptions.onRegisterApi = function(gridApi) {
        $scope.gridApi = gridApi;

        gridApi.edit.on.afterCellEdit($scope, function(rowEntity, colDef, newValue, oldValue) {
            if (newValue == oldValue) return;
            $scope.modified.items.push(rowEntity);
        });


        gridApi.pagination.on.paginationChanged($scope, function(newPage, pageSize) {
            var filtersData = $scope.memoryfilterData;
            filtersData.idx = newPage - 1;
            filtersData.sum = pageSize;
            $rootScope['idx'] = newPage;
            $scope.refreshData('expand-right', filtersData);
        });

        gridApi.selection.on.rowSelectionChanged($scope, function(scope) {
            var j = 0;
            for (var i = 0; i <= scope.grid.appScope.selected.items.length; i++) {
                if (scope.grid.appScope.selected.items[i] == scope.entity) {
                    j++;
                    break;
                }
            }
            // console.log("j="+j)
            if (j == 1) {
                scope.grid.appScope.selected.items.splice(i, 1);
            } else {
                scope.grid.appScope.selected.items.push(scope.entity)
            }
        });

        gridApi.core.on.filterChanged($scope, function() {
            var grid = this.grid;
            var filtersData = {
                idx: 0,
                sum: 10
            };
            angular.forEach(grid.columns, function(item) {
                if (item.enableFiltering) {
                    if (angular.isDefined(item.filters[0].term) && item.filters[0].term != '') {
                        if (angular.isUndefined(filtersData['role'])) {
                            filtersData['role'] = {};
                        }
                        filtersData['role'][item.field] = item.filters[0].term;
                    }
                }
            });
            $scope.memoryfilterData = filterData
            $scope.refreshData('expand-right', filtersData);
        });
    };


    var defaultFilterData = {
        "idx": 0,
        "sum": 10
    };

    $scope.memoryfilterData = {
        "idx": 0,
        "sum": 10
    }
    if ($rootScope['cmdbs'] != 'role') { $rootScope.idx = 1 }
    if (angular.isDefined($rootScope.idx) && $rootScope.cmdbs != "false") {
        $rootScope.cmdbs = 'role';
        defaultFilterData.idx = $rootScope.idx - 1;
    } else { $rootScope.cmdbs = ''; }
    $scope.ldloading = {};
    $scope.roleright = "";
    $scope.refreshData = function(style, filterData) {
        $scope.ldloading[style.replace('-', '_')] = true;
        if (angular.isUndefined(filterData)) {
            defaultFilterData.idx = $rootScope.idx - 1;
            filterData = defaultFilterData;
        }
        $scope.myData = [];

        api_user_data.fetchDataList("role", filterData).then(function(data) {
            var myData = Restangular.stripRestangular(data);
            // console.log("myData="+JSON.stringify(myData.list))
            // if($scope.myData.list.)
            $scope.gridOptions.totalItems = myData.totalNum;
            $scope.myData = myData.list;
            $scope.ldloading[style.replace('-', '_')] = false;
        }, function() {
            $scope.ldloading[style.replace('-', '_')] = false;
        });
    };

    $scope.refreshData('expand-right', defaultFilterData);

}]);